package com.ruicar.afs.cloud.product.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.uid.AfsSequenceGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.product.condition.ProductAtomCondition;
import com.ruicar.afs.cloud.product.condition.ProductTemplateCondition;
import com.ruicar.afs.cloud.product.entity.ProductTemplate;
import com.ruicar.afs.cloud.product.entity.ProductTemplateAtom;
import com.ruicar.afs.cloud.product.enums.StatusEnum;
import com.ruicar.afs.cloud.product.enums.StatusType;
import com.ruicar.afs.cloud.product.enums.TemplateCategory;
import com.ruicar.afs.cloud.product.service.ProductTemplateAtomService;
import com.ruicar.afs.cloud.product.service.ProductTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author changyu.gui
 * @version 1.0
 * @date 2020/4/27 20:09
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api("产品模板接口")
@RequestMapping("/productTemplate")
public class ProductTemplateController {

    private final ProductTemplateService service;
    private final ProductTemplateAtomService productTemplateAtomService;
    private final AfsSequenceGenerator afsSequenceGenerator;

    @PostMapping(value = "/queryTemplateList")
    @ApiOperation(value = "获取产品模块信息（分页）")
    public IResponse<IPage<ProductTemplate>> queryTemplateList(@RequestBody QueryCondition<ProductTemplateCondition> productCondition) {
        IPage<ProductTemplate> list = service.page(new Page(productCondition.getPageNumber(), productCondition.getPageSize()), Wrappers.<ProductTemplate>query().lambda()
                .like(StringUtils.isNotEmpty(productCondition.getCondition().getTemplateNumber()), ProductTemplate::getTemplateNumber, productCondition.getCondition().getTemplateNumber())
                .like(StringUtils.isNotEmpty(productCondition.getCondition().getTemplateName()), ProductTemplate::getTemplateName, productCondition.getCondition().getTemplateName())
                .eq(StringUtils.isNotEmpty(productCondition.getCondition().getTemplateCategory()), ProductTemplate::getTemplateCategory, productCondition.getCondition().getTemplateCategory())
                .eq(StringUtils.isNotEmpty(productCondition.getCondition().getIsEffective()), ProductTemplate::getIsEffective, productCondition.getCondition().getIsEffective())
                .eq(productCondition.getCondition().getVersionNumber()!=null, ProductTemplate::getVersionNumber, productCondition.getCondition().getVersionNumber())
                .orderByDesc(ProductTemplate::getCreateTime, ProductTemplate::getUpdateTime)
        );
        return IResponse.success(list);
    }

    @RequestMapping(value = "/effective", method = RequestMethod.POST)
    @ApiOperation(value = "设置产品模板有效")
    @SysLog("设置产品模板有效")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> effective(@ModelAttribute ProductTemplateCondition productTemplateCondition) {
        List<ProductTemplate> list = new ArrayList<>();
        service.listByIds(Arrays.asList(productTemplateCondition.getIds())).forEach(productTemplate -> {
            if (productTemplate != null && !AfsEnumUtil.key(StatusEnum.YES).equals(productTemplate.getIsEffective())) {
                productTemplate.setIsEffective(AfsEnumUtil.key(StatusEnum.YES));
                list.add(productTemplate);
            }
        });
        if (list.size() > 0) service.updateBatchById(list);
        return new IResponse<Boolean>().setData(true).setMsg("批量通过id设置数据有效成功");
    }

    @RequestMapping(value = "/invalid", method = RequestMethod.POST)
    @ApiOperation(value = "设置产品模板无效")
    @SysLog("设置产品模板无效")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> invalid(@ModelAttribute ProductTemplateCondition productTemplateCondition) {
        List<ProductTemplate> list = new ArrayList<>();
        for (ProductTemplate productTemplate : service.listByIds(Arrays.asList(productTemplateCondition.getIds()))) {
            if (productTemplate != null && !AfsEnumUtil.key(StatusEnum.NO).equals(productTemplate.getIsEffective())) {
                if (AfsEnumUtil.key(StatusEnum.YES).equals(productTemplate.getTemplateIsReference()))
                    return IResponse.fail("您选择模板" + productTemplate.getTemplateName() + "已使用,不能设置无效！");
                productTemplate.setIsEffective(AfsEnumUtil.key(StatusEnum.NO));
                list.add(productTemplate);
            }
        }
        if (list.size() > 0) service.updateBatchById(list);
        return new IResponse<Boolean>().setData(true).setMsg("批量通过id设置数据无效成功");
    }

    @RequestMapping(value = "/saveOrUpdateTemplate", method = RequestMethod.POST)
    @ApiOperation(value = "保存产品模板")
    public IResponse<ProductTemplate> saveOrUpdateTemplate(@ModelAttribute ProductTemplateCondition productTemplateCondition) {
        ProductTemplate productTemplate = new ProductTemplate();
        if (StrUtil.isBlank(productTemplateCondition.getTemplateCategory())) return IResponse.fail("模板类别不存在");
        ProductAtomCondition productAtomCondition = new ProductAtomCondition();
        //判断模板是否存在
        if (productTemplateCondition.getId() == null) {
            //模板不存在则新增
            int count = service.count(Wrappers.<ProductTemplate>query().lambda()
                    .eq(ProductTemplate::getTemplateName, productTemplateCondition.getTemplateName())
            );
            if (count > 0) return IResponse.fail("模板名称已存在");
            //获取编号
            String planNo = null;
            if(AfsEnumUtil.key(TemplateCategory.Father).equals(productTemplateCondition.getTemplateCategory())){
                Long seqno = afsSequenceGenerator.genNext(AfsEnumUtil.key(StatusType.PRODUCT_NUM_MB), StatusType.PRODUCT_NUM_MB.toString());
                planNo = AfsEnumUtil.key(StatusType.PRODUCT_NUM_MB) + DateUtil.year(DateUtil.date()) +StringUtils.leftPad(String.valueOf(seqno), 4, '0');// 编号
                productTemplate.setTemplateNumber(planNo);
            }else if(AfsEnumUtil.key(TemplateCategory.Son).equals(productTemplateCondition.getTemplateCategory())){
                Long seqno = afsSequenceGenerator.genNext(AfsEnumUtil.key(StatusType.PRODUCT_NUM_MBS), StatusType.PRODUCT_NUM_MBS.toString());
                planNo = AfsEnumUtil.key(StatusType.PRODUCT_NUM_MBS) + DateUtil.year(DateUtil.date()) +StringUtils.leftPad(String.valueOf(seqno), 4, '0');// 编号
            }
            productTemplate.setTemplateNumber(planNo);
            productTemplate.setTemplateName(productTemplateCondition.getTemplateName());
            productTemplate.setTemplateCategory(productTemplateCondition.getTemplateCategory());
            productTemplate.setIsEffective(AfsEnumUtil.key(StatusEnum.NO));
            //初次保存版本号从1开始
            productTemplate.setVersionNumber(1);
            service.save(productTemplate);
            productAtomCondition.setTemplateCategory(productTemplateCondition.getTemplateCategory());
            productAtomCondition.setAtomIsDefault(AfsEnumUtil.key(StatusEnum.YES));
            //初次保存序号从1开始
            productAtomCondition.setAtomSerialNumber(1);
            productAtomCondition.setProductTemplateId(productTemplate.getId());
        } else {
            //模板存在则根据状态判断更新还是新增
            productTemplate = service.getById(productTemplateCondition.getId());
            if (AfsEnumUtil.key(StatusEnum.YES).equals(productTemplate.getIsEffective())) {
                //模板有效则生成高版本的模板
                productTemplate.setTemplateName(productTemplateCondition.getTemplateName());
                productTemplate = productTemplateAtomService.saveTemplateInfo(productTemplate);
            } else {
                //模板未生效则更改信息
                productTemplate.setTemplateName(productTemplateCondition.getTemplateName());
                service.updateById(productTemplate);
            }
            ProductTemplateAtom atom1Atom = productTemplateAtomService.getOne(Wrappers.<ProductTemplateAtom>query().lambda()
                    .eq(ProductTemplateAtom::getProductTemplateId, productTemplate.getId()).orderByDesc(ProductTemplateAtom::getAtomSerialNumber), false);
            int atomSerialNumber = 0;
            if (atom1Atom != null) atomSerialNumber = atom1Atom.getAtomSerialNumber();
            productAtomCondition.setAtomSerialNumber(atomSerialNumber);
            productAtomCondition.setTemplateCategory(productTemplateCondition.getTemplateCategory());
            productAtomCondition.setProductTemplateId(Long.valueOf(productTemplate.getId()));
        }
        productTemplateAtomService.saveProductTemplateAtomDefault(productAtomCondition);
        return IResponse.success(productTemplate);
    }

    @RequestMapping(value = "/getProductTemplateInfo", method = RequestMethod.GET)
    @ApiOperation(value = "获取模板信息")
    public IResponse info(@ModelAttribute ProductTemplateCondition productTemplateCondition) {
        ProductTemplate productTemplate = service.getById(productTemplateCondition.getId());
        return new IResponse<>(productTemplate);
    }

    @PostMapping(value = "/getListProductTemplate")
    @ApiOperation(value = "获取产品模块信息（分页）")
    public IResponse<IPage<List<ProductTemplate>>> getListProductTemplate(@RequestBody QueryCondition<ProductTemplateCondition> productCondition) {
        IPage<List<ProductTemplate>> list = service.getListProductTemplate(new Page(productCondition.getPageNumber(), productCondition.getPageSize()), productCondition.getCondition());
        return IResponse.success(list);
    }

    @PostMapping(value = "/getListProductTemplateEffective")
    @ApiOperation(value = "获取生效产品模板信息（分页）")
    public IResponse<IPage<List<ProductTemplate>>> getListProductTemplateEffective(@RequestBody QueryCondition<ProductTemplateCondition> productCondition) {
        IPage<ProductTemplate> list = service.page(new Page(productCondition.getPageNumber(), productCondition.getPageSize()), Wrappers.<ProductTemplate>query().lambda()
                .like(StringUtils.isNotEmpty(productCondition.getCondition().getTemplateNumber()), ProductTemplate::getTemplateNumber, productCondition.getCondition().getTemplateNumber())
                .like(StringUtils.isNotEmpty(productCondition.getCondition().getTemplateName()), ProductTemplate::getTemplateName, productCondition.getCondition().getTemplateName())
                .eq(ProductTemplate::getIsEffective,AfsEnumUtil.key(StatusEnum.YES))
                .eq(ProductTemplate::getTemplateCategory,AfsEnumUtil.key(TemplateCategory.Father))
                .orderByDesc(ProductTemplate::getCreateTime, ProductTemplate::getUpdateTime)
        );
        return IResponse.success(list);
    }

}
